package zl.Dao;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
import zl.Entity.User;
import zl.Util.HibernateUtil;

import java.util.List;

@Repository
public class UserDao {
    public void saveUser(User user){
        Session session= HibernateUtil.openSession();
        Transaction tx=session.beginTransaction();
        session.save(user);
        tx.commit();
        HibernateUtil.closeSession();
    }

    public boolean selectUserByname(String username){
        Session session= HibernateUtil.openSession();
        Transaction tx=session.beginTransaction();
        String hql="from User where account=?1";
        List<User> users= session.createQuery(hql,User.class).setParameter(1,username).list();
        tx.commit();
        HibernateUtil.closeSession();
        return users.isEmpty();
    }

    public User selectUserByuser(User user){
        Session session= HibernateUtil.openSession();
        Transaction tx=session.beginTransaction();
        String hql="from User where account=?1 and password=?2";
        List<User> users= session.createQuery(hql,User.class).setParameter(1,user.getAccount()).setParameter(2,user.getPassword()).list();
        tx.commit();
        HibernateUtil.closeSession();
        if(users.isEmpty()){
            return null;
        }
        else
        {
            return users.get(0);
        }
    }
}
